﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Net.Messgae;
using pbc = global::Google.Protobuf.Collections;

public class RoomController : MonoBehaviour
{
    public UIRoomPlayer [] uiPlayers;

    void Awake()
    {
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageBeginMatchResp>(MessageId.BeginMatchResp,OnBeginMatchResp,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageCancelMatchResp>(MessageId.CancelMatchResp,OnCancelMatchResp,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageNotifyMatchInfo>(MessageId.NotifyMatchInfo,OnNotifyMatchInfo,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageFightReadyResp>(MessageId.FightReadyResp,OnFightReadyResp,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageNotifyGameStart>(MessageId.NotifyGameStart,OnNotifyGameStart,true);
        Waiting.SetTimeout(OnWaitTimeout,true);
    }

    void OnDestroy()
    {
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageBeginMatchResp>(MessageId.BeginMatchResp,OnBeginMatchResp,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageCancelMatchResp>(MessageId.CancelMatchResp,OnCancelMatchResp,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageNotifyMatchInfo>(MessageId.NotifyMatchInfo,OnNotifyMatchInfo,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageFightReadyResp>(MessageId.FightReadyResp,OnFightReadyResp,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageNotifyGameStart>(MessageId.NotifyGameStart,OnNotifyGameStart,false);
        Waiting.SetTimeout(OnWaitTimeout,false);
    }

    void OnWaitTimeout()
    {
        Warnning.Show("连接服务器超时",()=>{

            GoHome();

        });

        Disconnect();
    }

    void Start()
    {
        MessageBeginMatchReq req = new MessageBeginMatchReq();
        Model.Instance().msgHandler.SendMessage(MessageId.BeginMatchReq,req);

        Waiting.SetActive(true);
    }

    void UpdatePlayerInfos(pbc::RepeatedField<MatchPlayerInfo> players)
    {
        var roomInfo = Model.Instance().roomModel.roomInfo;
        if(null == roomInfo)
        {
            Debug.LogError("UpdatePlayerInfos reomInfo is null!");
            return;
        }

        foreach(var playerInfo in players)
        {
            int index = roomInfo.IndexOfPlayers(playerInfo);

            switch((MatchPlayerState)playerInfo.State)
            {
                case MatchPlayerState.None:
                case MatchPlayerState.Ready:
                    if(-1 == index)
                    {
                        roomInfo.players.Add(playerInfo);
                    }
                    else
                    {
                        roomInfo.players[index] = playerInfo;
                    }
                    break;
                case MatchPlayerState.Leave:
                    if(index != -1)
                    {
                        roomInfo.players.RemoveAt(index);
                    }
                    break;
            }
        }

        for(int i = 0; i < uiPlayers.Length; i++)
        {
            bool isLeave = true;

            foreach(var playerInfo in roomInfo.players)
            {
                if(playerInfo.Index == i + 1)
                {
                    uiPlayers[i].UpdateData(playerInfo);
                    isLeave = false;
                    break;
                }
            }

            if(isLeave)
            {
                uiPlayers[i].OnLeave();
            }
        }
    }

    void OnBeginMatchResp(uint msgID,MessageBeginMatchResp resp)
    {
        Waiting.SetActive(false);

        if(resp.Result != (int)ErrorCode.Successed)
        {
            Disconnect();

            Warnning.Show("匹配错误:" + resp.Result,()=>{

                GoHome();

            });
            return;
        }

        Model.Instance().roomModel.SetRoomInfo(new RoomInfo(resp.MatchId));

        UpdatePlayerInfos(resp.Players);
    }

    void OnNotifyMatchInfo(uint msgID,MessageNotifyMatchInfo resp)
    {
        UpdatePlayerInfos(resp.Players);
    }

    public void OnReadyClick()
    {
        var roomInfo = Model.Instance().roomModel.roomInfo;
        if(null == roomInfo)
        {
            Warnning.Show("未进入匹配房间");
            Debug.LogError("OnReadyClick reomInfo is null!");
            return;
        }

        if(!roomInfo.CanReady())
        {
            Warnning.Show("房间人数不足");
            return;
        }

        MessageFightReadyReq req = new MessageFightReadyReq();
        req.MatchId = roomInfo.MatchId;
        req.State = 1;
        Model.Instance().msgHandler.SendMessage(MessageId.FightReadyReq,req);

        Waiting.SetActive(true);
    }

    void OnFightReadyResp(uint msgID,MessageFightReadyResp resp)
    {
        Waiting.SetActive(false);

        if(resp.Result != (int)ErrorCode.Successed)
        {
            Warnning.Show("准备错误:" + resp.Result);
            return;
        }
    }

    void OnNotifyGameStart(uint msgID,MessageNotifyGameStart resp)
    {
        var roomInfo = Model.Instance().roomModel.roomInfo;
        if(null == roomInfo)
        {
            Debug.LogError("OnNotifyGameStart roomInfo is null!");
            return;
        }

        roomInfo.OnGameStart(resp);

        SceneHelper.LoadScene("battle");
    }

    void OnDisconnected()
    {
        Waiting.SetActive(false);

        Warnning.Show("连接服务器失败",()=>{

            GoHome();
            
        });
    }

    void OnCancelMatchResp(uint msgID,MessageCancelMatchResp resp)
    {
        Waiting.SetActive(false);

        if(resp.Result != (int)ErrorCode.Successed)
        {
            Disconnect();

            Warnning.Show("取消匹配错误:" + resp.Result,()=>{

                GoHome();

            });
            return;
        }

        Disconnect();

        GoHome();
    }

    void Disconnect()
    {
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,false);

        Model.Instance().networkManager.DisconnectTcp();
    }

    void GoHome()
    {
        SceneHelper.LoadScene("home");
    }

    public void OnBackClick()
    {
        var roomInfo = Model.Instance().roomModel.roomInfo;
        if(null == roomInfo)
        {
            Disconnect();

            GoHome();
        }
        else
        {
            MessageCancelMatchReq req = new MessageCancelMatchReq();
            req.MatchId = roomInfo.MatchId;
            Model.Instance().msgHandler.SendMessage(MessageId.CancelMatchReq,req);

            Waiting.SetActive(true);
        }
    }
}
